package com.cn.esermis.config;
import com.cn.esermis.utils.TableCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component
public class TableScheduler {

    private final TableCreator tableCreator;

    @Autowired
    public TableScheduler(TableCreator tableCreator) {
        this.tableCreator = tableCreator;
    }

    // 每月最后一天 23:59 执行
    @Scheduled(cron = "0 0 0 * * 1")
    public void preCreateNextMonthTable() {
        // 计算下个月的表后缀（如当前为202310，下个月为202311）
        LocalDateTime nextMonth = LocalDateTime.now().plusMonths(1);
        String nextMonthSuffix = nextMonth.format(DateTimeFormatter.ofPattern("yyyyMM"));
        tableCreator.createTableIfAbsent("air_monitor_hour_record", nextMonthSuffix);
        tableCreator.createTableIfAbsent("air_monitor_minute_record", nextMonthSuffix);
        tableCreator.createTableIfAbsent("water_monitor_hour_record", nextMonthSuffix);
        tableCreator.createTableIfAbsent("water_monitor_minute_record", nextMonthSuffix);
    }
}